package com.apexwear.apexutils.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.RecyclerView;

import com.apexwear.apexutils.R;
import com.apexwear.apexutils.api.OnItemClickListener;
import com.apexwear.apexutils.model.Device;

import java.util.List;

public class AdapterDeviceList extends RecyclerView.Adapter<AdapterDeviceList.DeviceHold> {
    private Context mContext;
    private List<Device> deviceList;
    OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public AdapterDeviceList(Context mContext, List<Device> deviceList) {
        this.mContext = mContext;
        this.deviceList = deviceList;
    }

    @NonNull
    @Override
    public DeviceHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View adapterView = LayoutInflater.from(mContext).inflate(R.layout.adapter_device_list, parent, false);
        return new DeviceHold(adapterView);
    }

    @Override
    public void onBindViewHolder(@NonNull DeviceHold holder, int position) {
        if (deviceList == null || deviceList.isEmpty()) {
            return;
        }
        holder.nameText.setText(deviceList.get(position).getNameTxt());
        holder.tagText.setText(deviceList.get(position).getTagTxt());
        holder.bindButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始绑定手表
                if (onItemClickListener != null) {
                    onItemClickListener.clickListener(position);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return deviceList == null ? 0 : deviceList.size();
    }

    class DeviceHold extends RecyclerView.ViewHolder {
        AppCompatButton bindButton;
        TextView nameText;
        TextView tagText;

        public DeviceHold(@NonNull View itemView) {
            super(itemView);
            bindButton = itemView.findViewById(R.id.bind_watch);
            nameText = itemView.findViewById(R.id.watch_name);
            tagText = itemView.findViewById(R.id.watch_tag);
        }
    }

    public void destroyAdapter() {
        mContext = null;
        if (deviceList != null) {
            deviceList.clear();
            deviceList = null;
        }
        onItemClickListener = null;
    }
}
